//
import {ESApp} from "@extscreen/es3-vue"
import {LaunchKey} from "./useApi";
import {ESNativeRouter, Router} from "@extscreen/es3-router";
import {ESDevelop, ESLog, ESLogLevel, ESToast} from "@extscreen/es3-core";
import {NavigationFailure} from "@extscreen/es3-router/dist/src/errors";

export const launchRedirectType = {
  router: 1, out: 2
}


export interface Launch {

  install(app: ESApp): void

  init(...params: any[]): Promise<any>;

  launch(item: LaunchParams): Promise<void | NavigationFailure | undefined>;

  jumpLogin(item?: any): void;

  jumpVipPay(item?: any): void
}

export function createLaunch(): Launch {

  const TAG = 'Launch'

  let log: ESLog
  let router: Router
  let nativeRouter: ESNativeRouter
  let develop: ESDevelop
  let toast: ESToast

  function init(...params: any[]): Promise<any> {
    log = params[0]
    console.log('log==',log)
    router = params[1]
    nativeRouter = params[2]
    develop = params[3]
    toast=params[4]
    return Promise.resolve();
  }

  function launch(item: LaunchParams):  Promise<void | NavigationFailure | undefined> {
    if (log.isLoggable(ESLogLevel.DEBUG)) {
      log.d(TAG, '------launch------->>>>', item)
    }
    if (!item.item) {
      if (log.isLoggable(ESLogLevel.DEBUG)) {
        log.d(TAG, '------launch-----error-->>>>')
      }
      return Promise.reject()
    }
    const data = item.item
    const redirectType = data.redirectType;
    if (redirectType==0) {
      return launchEs(data)
    }else if(redirectType==1) {
      return launchInner(data)
    } else if(redirectType==3) {
      return launchOuter(data)
    }
    return Promise.reject()
  }

  //跳转快应用
  function launchEs(data: LaunchItem): Promise<void | NavigationFailure | undefined> {
    let url = data.pageUrl ? data.pageUrl : data.action;
    if (url) {
      return launchNativeAppByScheme(url)
    } else {
      if (log.isLoggable(ESLogLevel.ERROR)) {
        // log.e("Intent Utils","跳转地址出错")
      }
    }
    return Promise.reject()
  }

  //内部跳转
  function launchInner(data): Promise<void | NavigationFailure | undefined> {
    const argsStr = data.innerArgs;
    const args = JSON.parse(argsStr)
    if (log.isLoggable(ESLogLevel.DEBUG)) {
      log.d(TAG, '------launch---params---->>>>', args.params)
    }
    return router.push({
      name: args.url,
      params: args.params
    });
  }

  //外部跳转
  function launchOuter(data: LaunchItem): Promise<void | NavigationFailure | undefined> {
    const action = data.action;
    const params: Array<LaunchActionParams> = JSON.parse(action.jsonStr || '[]')
    if (log.isLoggable(ESLogLevel.DEBUG)) {
      log.d(TAG, '------launchOuter---params---->>>>', params)
    }
    const type = action.type.toUpperCase()
    const packageName = action.packageName
    let activityPath = packageName + "/" + action.activityName
    if (!action.actionName) {
      activityPath = ''
    }
    if (type === 'URL') {
      const scheme = action.scheme
      return launchNativeAppByScheme(scheme, false, packageName, params)
    } else if (type === 'ACTION') {
      const actionView = action.actionName
      return launchNativeAppByAction(packageName, actionView, params)
    } else if (type === 'ACTIVITY') {
      return launchNativeAppByActivity(packageName, activityPath, params)
    }
    return Promise.reject()
  }

  function launchNativeAppByAction(packageName: string, actionView: string='', params: Array<LaunchActionParams> = []) {
    let args: Array<any> = []
    args.push(['-a', actionView]);
    args.push(['-p', packageName]);
    if (params && params.length > 0) {
      for (const item of params) {
        const key = item.key
        const value = item.value
        const type = item.type
        const mParam = dealParams(key, value, type)
        if (mParam && mParam.length > 0) {
          args.push(mParam)
        }
      }
    }
    return nativeRouter.launch(args);
  }

  function launchNativeAppByScheme(scheme, userLocalPkg = true, packageName = "", params: Array<LaunchActionParams> = []) {
    let args: Array<any> = []
    args.push(['-d', scheme]);
    if (!scheme.includes('-p')) {
      if (userLocalPkg) {
        const mPackageName = develop.getPackageName()
        args.push(['-p', mPackageName]);
      } else if (packageName) {
        args.push(['-p', packageName]);
      }
    }
    if (params && params.length > 0) {
      for (const item of params) {
        const key = item.key
        const value = item.value
        const type = item.type
        const mParam = dealParams(key, value, type)
        if (mParam && mParam.length > 0) {
          args.push(mParam)
        }
      }
    }
    // console.log('args:',args)
    return nativeRouter.launch(args);
  }

  function launchNativeAppByActivity(packageName, activityPath, params: Array<LaunchActionParams> = []) {
    let args: Array<any> = []
    if (activityPath) {
      args.push(['-n', activityPath]);
    }else{
      args.push(['-c', "android.intent.category.LAUNCHER"]);
    }
    args.push(['-p', packageName]);
    if (params && params.length > 0) {
      for (const item of params) {
        const key = item.key
        const value = item.value
        const type = item.type
        const mParam = dealParams(key, value, type)
        if (mParam && mParam.length > 0) {
          args.push(mParam)
        }
      }
    }
    console.log('args:', args)
    return nativeRouter.launch(args);
  }

  function dealParams(key, value, type) {
    let param: Array<string> = []
    switch (type.toLowerCase()) {
      case "string":
        param = ['--es', key, value];
        break;
      case "int":
        param = ['--ei', key, value];
        break;
      case "boolean":
        param = ['--ez', key, value];
        break;
    }
    return param
  }

  function jumpLogin(item?: any) {
    //统一跳转登录的页面，每个业务各自实现具体逻辑
  }

  function jumpVipPay(item?: any) {
    //统一跳转支付的页面，每个业务各自实现具体逻辑
  }

  return {
    install: function (app: ESApp) {
      const instance = this
      app.provide(LaunchKey, instance)
    },
    init,
    launch,
    jumpLogin,
    jumpVipPay
  }
}

const launch = createLaunch()
export default launch
